/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.demo.xpath;

import org.vacoor.nothing.common.util.Resources;
import org.vacoor.nothing.common.xml.JAXP;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

import javax.xml.namespace.NamespaceContext;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * XPath Demo
 *
 * @author Vacoor
 */
public class XPathDemo {
    public static class User {
        String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }

    public static void main(String[] args) throws XPathExpressionException, IOException, SAXException {
        InputStream in = Resources.getResourceAsStream("test.xml");
        Document parse = JAXP.createDOMBuilder(null).parse(in);

        Element root = parse.getDocumentElement();
        final String namespaceURI = root.getNamespaceURI();

        XPathFactory factory = XPathFactory.newInstance();
        XPath xpath = factory.newXPath();
        SimpleNamespaceContext nc = new SimpleNamespaceContext();
        xpath.setNamespaceContext(nc);
        nc.put("n", namespaceURI);

        User u = new User();
        u.setName("xx");
        XPathExpression exp = xpath.compile("/n:mappings");
        Object o = exp.evaluate(root);
        System.out.println(o);
        XPathExpression xpe = xpath.compile("/mappings/text()[2]");
        System.out.println(xpe.evaluate(parse));
    }

    public static class SimpleNamespaceContext implements NamespaceContext {
        private Map<String, String> namespaces = new HashMap<String, String>();

        public void put(String prefix, String namespace) {
            namespaces.put(prefix, namespace);
        }

        @Override
        public String getNamespaceURI(String prefix) {
            return namespaces.get(prefix);
        }

        @Override
        public String getPrefix(String namespaceURI) {
            for (Map.Entry<String, String> e : namespaces.entrySet()) {
                if (e.getValue().equals(namespaceURI)) {
                    return e.getKey();
                }
            }
            return null;
        }

        @Override
        public Iterator getPrefixes(String namespaceURI) {
            return Arrays.asList(getPrefix(namespaceURI)).iterator();
        }
    }
}
